package com.forfunnet.minjian.ui.adapter;

/**
 * Created by Lei on 2014/12/10.
 */

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.forfunnet.minjian.R;
import com.forfunnet.minjian.ui.LoginActivity_;
import com.forfunnet.minjian.ui.MainActivity_;
import com.jakewharton.salvage.RecyclingPagerAdapter;
import com.viewpagerindicator.IconPagerAdapter;

import java.util.List;

/**
 * ImagePagerAdapter
 *
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2014-2-23
 */
public class GuidePagerAdapter extends RecyclingPagerAdapter implements IconPagerAdapter {
    private Activity context;
    private List<Integer> imageList;

    private int           size;
    private boolean       isInfiniteLoop;

    public GuidePagerAdapter(Activity context, List<Integer> imageList) {
        this.context = context;
        this.imageList = imageList;
        this.size = imageList.size();
        isInfiniteLoop = false;
    }

    @Override
    public int getIconResId(int index) {
        return R.drawable.pager_indicator;
    }

    @Override
    public int getCount() {
        // Infinite loop
        return isInfiniteLoop ? Integer.MAX_VALUE : size;
    }

    /**
     * get really position
     *
     * @param position
     * @return
     */
    private int getPosition(int position) {
        return isInfiniteLoop ? position % size : position;
    }

    @Override
    public View getView(int position, View view, ViewGroup container) {
        ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = context.getLayoutInflater().inflate(R.layout.guide_enter, null);
            holder.imageView = (ImageView)view.findViewById(R.id.image);
            holder.textView = (TextView)view.findViewById(R.id.enter);
            if (position == 2) {
                holder.textView.setVisibility(View.VISIBLE);
                holder.textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MainActivity_.intent(context).start();
                        context.finish();
                    }
                });
            }
            view.setTag(holder);
        } else {
            holder = (ViewHolder)view.getTag();
        }
        holder.imageView.setImageResource(imageList.get(getPosition(position)));
        return view;
    }

    private static class ViewHolder {
        ImageView imageView;
        TextView textView;
    }

    /**
     * @return the isInfiniteLoop
     */
    public boolean isInfiniteLoop() {
        return isInfiniteLoop;
    }

    /**
     * @param isInfiniteLoop the isInfiniteLoop to set
     */
    public GuidePagerAdapter setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
        return this;
    }
}